﻿using System.Linq;

namespace ComeSeeThis_MVC2.Models
{
    public class User
    {
        //private readonly AspNetStuffEntities context = new AspNetStuffEntities();

        #region Queries

        /// <summary>
        ///  Check if a user is a member of a role
        /// </summary>
        /// <param name="userName">UserName</param>
        /// <param name="roleNames">Comma seperated string of role names</param>
        /// <returns>True if user is a member of any of the roles, otherwise false</returns>
        public static bool IsInRole(string userName, string roleNames)
        {
            var context = new AspNetStuffEntities();
            // String of roleNames are seperated by these characters
            char[] delimiters = { ',' };

            // Get array of role names
            string[] roles = roleNames.Split(delimiters);

            // Create user object
            var theUser = context.aspnet_Users.FirstOrDefault(x => x.LoweredUserName == userName.ToLower());

            // Iterate through the array of roles, return true if the user is a member of any of them
            // Otherwise return false
            //return roles.Select(role => context.aspnet_Roles.FirstOrDefault(x => x.LoweredRoleName == role.ToLower())).Any(theRole => theUser.aspnet_Roles.Contains(theRole));
            foreach (var role in roles)
            {
                //var role1 = role;
                var theRole = context.aspnet_Roles.FirstOrDefault(x => x.LoweredRoleName == role.ToLower());
                if (theUser.aspnet_Roles.Contains(theRole)) return true;
            }

            // User was not in any of the roles, so return fals
            return false;

        }

        
        #endregion

    }
}